import React, { ReactNode, useEffect, useRef } from 'react';
import './HomePage.scss';
import { BrowserRouter, Routes, Route, Link, Navigate, useNavigate, Outlet, useLocation, useSearchParams } from 'react-router-dom'
import { useState } from 'react';
import { HomeOutlined, ClockCircleOutlined, FileTextOutlined, FileProtectOutlined, DeleteOutlined, PlusOutlined, AppstoreAddOutlined, FolderOutlined, ExclamationCircleOutlined, FundProjectionScreenOutlined } from '@ant-design/icons';
import { commonErrorMsg, commonSuccessMsg, isEmpty, makeClassNameList, toastShort } from '../../utils';
import AddGroupModal from './modal/AddGroupModal';
import systemApi from '../../api/system';
import { DocGroupItem } from '../../utils/types';
import DocGroupItemKit from './modal/DocGroupItemKit';
import { MenuProps, Modal } from 'antd';
import LoadingWapper from '../../components/loading/LoadingWapper';
import { FolderUpload } from '@icon-park/react';
import { saasConfig } from '../../config/theme-config';

interface RoutItem {
    routeName: string
    routePath: string
    search: string
    icon: ReactNode
}

const HomePage = () => {

    const addGroudModalRef = useRef<any>(null);
    const navigate = useNavigate();
    const [searchParams, setSearchParams] = useSearchParams();
    const routerLocation = useLocation();
    const [curentRoutePath, setCurrentRoutePath] = useState(routerLocation.pathname);

    const [docGroupList, setDocGroupList] = useState<DocGroupItem[]>([]);
    const [currentFocusDocGroup, setCurrentFocusDocGroup] = useState<DocGroupItem>(null);
    const [currentActiveDocGroup, setCurrentActiveDocGroup] = useState<DocGroupItem>(null);

    const tempDocGroup = useRef<DocGroupItem>(null);
    const [deleteLoading, setDeleteLoading] = useState(false);
    const [loading, setLoading] = useState(true);

    const [routeList, setRouteList] = useState<RoutItem[]>([
        {
            routeName: "最近打开",
            icon: <ClockCircleOutlined className='side-bar-item-icon' />,
            search: '?layout-type=card&protectland-type=0&sort-type=1',
            routePath: 'recently-opened'
        },
        {
            routeName: "所有规划",
            icon: <FileTextOutlined className='side-bar-item-icon' />,
            search: '?layout-type=card&protectland-type=0&sort-type=1',
            routePath: 'all-projects'
        },
        // {
        //     routeName: "共享文档",
        //     icon: <FileProtectOutlined className='side-bar-item-icon' />,
        //     search: '?layout-type=card&sort-type=4&pfid=641bced071638dec22cc66d1',
        //     routePath: 'share-files'
        // },
        // {
        //     routeName: "统计分析",
        //     icon: <FundProjectionScreenOutlined className='side-bar-item-icon' />,
        //     search: '?layout-type=card&sort-type=1',
        //     routePath: 'statistical-analysis'
        // },
        {
            routeName: "回收站",
            icon: <DeleteOutlined className='side-bar-item-icon' />,
            search: '?layout-type=card&protectland-type=0&sort-type=1',
            routePath: 'recycling-bin'
        }
    ])

    const [shareFileRoute, setShareFileRoute] = useState<RoutItem>({
        routeName: "共享云盘",
        icon: <FolderUpload theme="outline" size="20" style={{ marginTop: '3px' }} fill={saasConfig.colorConfig.colorPrimary} />,
        // icon: <div><img style={{width: 24, height: 24}} src={require('./../../assets/image/file-upload-small-icon.png')}/></div>,
        search: '?layout-type=card&sort-type=4&pfid=641bced071638dec22cc66d1',
        routePath: 'share-files'
    })

    const [shareFileCount, setShareFileCount] = useState<number>(0);

    const [docGroupSearchParams, setDocGroupSearchParams] = useState<string>("?layout=card&belong-type=0&sort-type=1");

    useEffect(() => {
        const { search, pathname } = routerLocation;
        let _routeList = routeList;
        const findRouteItem = _routeList.find(routeItem => {
            const fullRoutePath = '/home/' + routeItem.routePath;
            if (fullRoutePath == pathname) {
                routeItem.search = search;
                return routeItem;
            }
        })
        if (findRouteItem) {
            setCurrentFocusDocGroup(null);
            setCurrentActiveDocGroup(null);
            setRouteList([..._routeList]);
        } else {

        }
        setCurrentRoutePath(pathname);

    }, [routerLocation])

    useEffect(() => {
        queryDocGroupList();
    }, []);

    const formItemLayout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 22 },
    };

    const queryDocGroupList = () => {
        let params = {
            page: 1,
            size: 100,
        };
        setLoading(true);
        systemApi.queryDocGroupList(params)
            .then(res => {
                console.log("测试---->", res)
                setLoading(false);
                const _docGroupList = res.data.list;
                const sectionalizationId = searchParams.get('sectionalization-id');
                if (!isEmpty(sectionalizationId)) {
                    const findDocGroup = _docGroupList.find(ele => {
                        return ele.id == sectionalizationId;
                    });
                    if (findDocGroup) {
                        setCurrentActiveDocGroup(findDocGroup);
                    }
                }
                setDocGroupList(_docGroupList)
            })
            .catch(err => {
                setLoading(false);
                console.log("err---->", err)
            })
    };

    const jumpToHomePageSubRoute = (route: RoutItem) => {
        navigate('/home/' + route.routePath + route.search);
    };

    const checkCurrentRouteActive = (route: RoutItem) => {
        const pathStepList = curentRoutePath.split('/');
        if (pathStepList.length && pathStepList[pathStepList.length - 1] == route.routePath) {
            return true;
        }
        return false;
    };

    const handleAddGroup = () => {
        addGroudModalRef.current.openModal();
    }

    const onReNameDocGroup = (docGroup: DocGroupItem) => {
        addGroudModalRef.current.openModal(docGroup);
    }

    useEffect(() => {
        getShareFileCount();
    }, [])

    const getShareFileCount = () => {
        let params = {
            page: 1,
            size: 9999,
        }
        systemApi.queryShareFileList(params)
            .then(res => {
                console.log("所有的共享文件----->", res)
                const fileList = res.data.list.filter(item => {
                    return item.url && item.url !== 'url';
                })
                setShareFileCount(fileList.length)
            })
            .catch(err => {
                console.log("err---->", err)
            })
    }

    const [modal, contextHolder] = Modal.useModal();

    const onDeleteDocGroup = (docGroup: DocGroupItem) => {
        if (docGroup.isDefault) {
            return toastShort('error', '默认分组不可删除！');
        }
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认删除此分组？请确保此分组下无规划报告',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk: confirmToDeleteDocGroup,
            okButtonProps: { loading: deleteLoading }
        });
        tempDocGroup.current = docGroup;
    }

    const _onFinish = () => {
        toastShort('success', commonSuccessMsg);
        queryDocGroupList();
    }

    const confirmToDeleteDocGroup = () => {
        let params = {
            ids: [tempDocGroup.current.id],
        };
        setDeleteLoading(true);
        systemApi.deleteDocGroup(params)
            .then(res => {
                _onFinish();
                setDeleteLoading(false);
            })
            .catch(err => {
                setDeleteLoading(false);
                toastShort('error', commonErrorMsg)
            })
    }

    const onClicDocGroup = (docGroup: DocGroupItem) => {
        navigate('/home/' + 'doc-group' + docGroupSearchParams + `&sectionalization-id=${docGroup.id}`);
        setCurrentActiveDocGroup(docGroup)
    }

    const handleJumpToWebSite = () => {
        window.open("https://www.zhbhd.cn/");
    }

    return (
        <div className='flex-row home-page-container'>
            <div className='flex-col side-bar'>
                {
                    routeList.map((route, routeIndex) => {
                        return (
                            <div
                                key={routeIndex + ''}
                                onClick={() => jumpToHomePageSubRoute(route)}
                                className={makeClassNameList(['flex-row', 'side-bar-item', checkCurrentRouteActive(route) ? 'active' : null])}
                            >
                                <div className='flex-row side-bar-item-icon-box'>
                                    {route.icon}
                                </div>
                                <p className='side-bar-item-name'>{route.routeName}</p>
                            </div>
                        )
                    })
                }
                <div className='flex-col group-list'>
                    <div className='flex-row group-list-header'>
                        <p className='group-list-header-title'>分组</p>
                        <div
                            className='flex-row group-list-header-add'
                            onClick={handleAddGroup}
                        >
                            <PlusOutlined />
                        </div>
                    </div>
                    <div className='flex-col group-list-content'>
                        {
                            docGroupList.map((group, groupIndex) => {
                                return (
                                    <DocGroupItemKit
                                        group={group}
                                        key={groupIndex + ''}
                                        onReNameDocGroup={onReNameDocGroup}
                                        onDeleteDocGroup={onDeleteDocGroup}
                                        currentFocusDocGroup={currentFocusDocGroup}
                                        currentActiveDocGroup={currentActiveDocGroup}
                                        handleSetCurrentFocusDocGroup={setCurrentFocusDocGroup}
                                        onClickItem={onClicDocGroup}
                                    />
                                )
                            })
                        }
                    </div>
                    <LoadingWapper
                        loading={loading}
                        style={{ paddingBottom: '49%' }}
                    />
                </div>
                <div className='share-file-sidebar'>
                    <div className='share-file-sidebar-border'></div>
                    <div
                        onClick={() => jumpToHomePageSubRoute(shareFileRoute)}
                        className={makeClassNameList(['flex-row', 'side-bar-item', checkCurrentRouteActive(shareFileRoute) ? 'active' : null])}
                    >
                        <div className='flex-row side-bar-item-icon-box' style={{color: saasConfig.colorConfig.colorPrimary}}>
                            {shareFileRoute.icon}
                        </div>
                        <p className='side-bar-item-name'>{shareFileRoute.routeName}</p>
                        {
                            shareFileCount ?
                                <div className='side-bar-item-count' style={{ color: saasConfig.colorConfig.colorPrimary}}>{shareFileCount}</div>
                                :
                                null
                        }
                    </div>
                </div>
                <div
                    className='flex-col side-nav-footer link-text'
                    onClick={handleJumpToWebSite}
                >
                    <span className='side-nav-footer-desc'>北京青远生态·技术支持</span>
                </div>
            </div>
            <div className='home-page-content'>
                <Outlet />
            </div>
            <AddGroupModal
                ref={addGroudModalRef}
                onFinish={_onFinish}
            />
            {contextHolder}
        </div>
    )
}

export default HomePage;